package ui.logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class FileLogger implements Runnable, LogAcceptor {
	private static final String EVENTS_LOG = "./log/events.log";
	private Queue<LogEvent> q = new ConcurrentLinkedQueue<LogEvent>();
	private Thread runner = new Thread(this, "File logger thread");
	
	public FileLogger() {
		new File(EVENTS_LOG).delete();	
	}

	public void run() {
		
		while (true) {
			if (!q.isEmpty()) {
				print(q.poll());
			} else
				try {
					synchronized (this) {
						wait();
					}
				} catch (InterruptedException e) {
				}
		}

	}

	private void print(LogEvent le) {
		try {
			// let's dirt the momry!
			//BufferedWriter writer = new BufferedWriter();
			PrintWriter writer  = new PrintWriter(new FileWriter(EVENTS_LOG, true));
			writer.println(new Date() + "[" + le.getClass() + "] " + le.getMessage());
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void show(LogEvent le) {
		q.add(le);
		if (!runner.isAlive())
			runner.start();
		else
			synchronized (this) {
				notifyAll();
			}

	}

}
